package com.auxgroup.hr.front.site.inteceptor;

import org.apache.commons.lang.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 获取session内容的sessionScope注解处理类
 * @author lv-PC
 *
 */
public class SessionGainMethodArgumentResolver implements
		HandlerMethodArgumentResolver {

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		// 让方法和参数，两种target通过
		if (parameter.hasParameterAnnotation(SessionGain.class)) {
			return true;
		}
		if (parameter.getMethodAnnotation(SessionGain.class) != null) {
			return true;
		}
		return false;
	}

	@Override
	public Object resolveArgument(MethodParameter parameter,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
			WebDataBinderFactory binderFactory) throws Exception {
		String annoVal = null;
		if (parameter.getParameterAnnotation(SessionGain.class) != null) {
			annoVal = parameter.getParameterAnnotation(SessionGain.class).value();
		} else if (parameter.getMethodAnnotation(SessionGain.class) != null) {
			annoVal = parameter.getMethodAnnotation(SessionGain.class) != null ? StringUtils
					.defaultString(parameter.getMethodAnnotation(
							SessionGain.class).value()) : StringUtils.EMPTY;
		}
		if (webRequest.getAttribute(annoVal, RequestAttributes.SCOPE_SESSION) != null) {
			return webRequest.getAttribute(annoVal,
					RequestAttributes.SCOPE_SESSION);
		} 
		return null;
	}
}